<!-- eslint-disable max-len -->
<template>
  <a-modal v-model="visible" :maskClosable="false" :confirmLoading="confirmLoading" :width="608" :title="$t('uploadFile')" @cancel="handCancel" @ok="uploadOk">
    <a-form-model
      class="model-content"
      ref="createModal"
      :model="formUploadFile"
      :rules="uploadRules"
    >
      <!-- 摘要算法 -->
      <a-form-model-item
        :label="$t('zysf')"
        prop="hashAlgorithm"
      >
        <a-select
          v-model="formUploadFile.hashAlgorithm"
          showSearch
          allow-clear
          :placeholder="$t('pleaseSelect')"
          optionFilterProp="children"
          :filterOption="$commonFun.filterOption"
          style="width: 100%"
        >
          <a-select-option
            v-for="(key,val,index) in digestAlgorithm"
            :key="index"
            :value="parseInt(val,10)"
          >
            {{ key }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <a-checkbox
        style="position:absolute;right:0"
        :checked="isManualEntry"
        @change="isManualEntry=$event.target.checked">
        {{ $t('manualInput') }}
      </a-checkbox>
      <!-- 摘要值 -->
      <a-form-model-item
        :label="$t('zyz')"
      >
        <!-- 手动输入 -->
        <a-textarea
          v-if="isManualEntry"
          style="width: 100%"
          v-model="formUploadFile.checksum"
          :placeholder="$t('pleaseInput')"
          :rows="4"
        >
        </a-textarea>
        <!-- 自动填充 -->
        <a-textarea
          v-else
          style="width: 100%"
          disabled
          :rows="4"
          v-model="fileInfor.fileObject[digestAlgorithm[formUploadFile.hashAlgorithm]]"
        ></a-textarea>
      </a-form-model-item>
      <!-- 版本文件 -->
      <a-form-model-item>
        <template slot="label">
          <span class="requiredSty">
            {{ $t('versionFile') }}
          </span>
        </template>
        <a-input
          ref="userNameInput"
          readOnly
          :value="fileInfor.fileObject.fileName"
          :placeholder="$t('pleaseUpload')"
        >
          <a-icon
            @click="upload"
            slot="suffix"
            type="upload"
          />
        </a-input>
        <chunk-upload
          ref="uploadPlug"
          :showDom="false"
          fileStoreField="fileObject"
          :recordData="fileInfor"
          uploadType="8"
          :userPartUrl="true"
          :size="20*1024*1024*1024"
          :hashAlgorithm="formUploadFile.hashAlgorithm"
        >
        </chunk-upload>
      </a-form-model-item>
      <!-- 原始版本 -->
      <a-form-model-item prop="primitiveVersion" :class="{hideprim: upgradePackType!==2}">
        <template v-slot:label>
          <span>{{ $t('originalVersion') }}</span>
          <question-mark-tip
            :tip-title="$t('scwjsourceTip')"
            :popupContainer="$commonFun.getPopupContainer"
          ></question-mark-tip>
        </template>
        <a-input :disabled="disableOriginVersion" v-model="formUploadFile.primitiveVersion" :placeholder="$t('pleaseInput')"></a-input>
        <!-- <a-select :disabled="disableOriginVersion" mode="tags" v-model="formUploadFile.primitiveVersion" :placeholder="$t('pleaseSelect')" @change="handleChange"> -->
        <!-- <a-select :disabled="disableOriginVersion" show-search  v-model="formUploadFile.primitiveVersion" :placeholder="$t('pleaseSelect')"> -->
          <!-- <a-select-option v-for="(item,index) in verisonList" :key="index" :value="item">
            {{ item }}
          </a-select-option>
        </a-select> -->
      </a-form-model-item>
      <!-- 预计安装时间 -->
      <a-form-model-item :label="$t('estimatedInstallTime')+'(s)' " prop="installSec">
        <a-input-number
          style="width: 100%"
          v-model="formUploadFile.installSec"
          :placeholder="$t('pleaseInput')+$t('estimatedInstallTime')"
        ></a-input-number>
      </a-form-model-item>
      <!-- 超时时长 -->
      <a-form-model-item :label="$t('timeout')+'(s)' " prop="timeoutSec">
        <a-input-number
          style="width: 100%"
          v-model="formUploadFile.timeoutSec"
          :placeholder="$t('pleaseInput')+$t('timeout')"
        ></a-input-number>
      </a-form-model-item>
      <!-- 文件烧写类型 -->
      <a-form-model-item :label="$t('file')+$t('sxType')" prop="fileReprogramType">
        <a-select
          v-model="formUploadFile.fileReprogramType"
          showSearch
          :placeholder="$t('pleaseSelect')+$t('file')+$t('sxType')"
          optionFilterProp="children"
          :filterOption="$commonFun.filterOption"
          style="width: 100%"
        >
          <a-select-option
            v-for="(item,index) in dllNameDictCode"
            :key="index"
            :value="item.code"
            :title="item.name"
          >{{ item.name }}</a-select-option>
        </a-select>
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>
<script>
import FormModel from '@/components/SelfModal/FormModel'
import ChunkUpload from '@/components/Upload/ChunkUpload'
import { mapState } from 'vuex'
import { checkIsRangeInteger,checkVersionNameWithOutV } from '@/utils/validate'
import QuestionMarkTip from '@/views/components/QuestionMarkTip'
const initForm = {
  hashAlgorithm: 1
}
export default {
  name: 'UploadVersionFile',
  components: { FormModel, ChunkUpload, QuestionMarkTip },
  props: {
    upgradePackType: {
      type: Number,
      default: undefined
    },
    modelCode: {
      type: String,
      default: undefined
    },
    ecuId: {
      type: String,
      default: undefined
    },
    softwareCode: {
      type: String,
      default: undefined
    },
    isConfigFile: {
      type: Number,
      default: undefined
    },
    versionNumber: {
      type: String,
      default: undefined
    },
    uploadFile: {
      type: Array,
      default: () => { return [] }
    }
  },
  computed: {
    ...mapState({
      // 摘要算法
      digestAlgorithm: (state) => state.dict.digestAlgorithm
    })
  },
  data () {
    let validatePrimitive = (rule, value, callback) => {
      if (this.upgradePackType === 2) {
        callback(new Error(this.$t('pleaseInput')));
      } else {
        callback();
      }
    };
    let _self = this
    return {
      visible: false,
      confirmLoading: false,
      formUploadFile: { ...initForm },
      fileInfor: { fileObject: {} },
      uploadRules: {
        hashAlgorithm: [{ required: true, message: this.$t('pleaseSelect') }],
        // lxhmodifyxccode
        // eslint-disable-next-line max-len
        installSec: [{ required: true, message: this.$t('pleaseInput') }, { validator: checkIsRangeInteger(1, 2147483647) }],
        // eslint-disable-next-line max-len
        timeoutSec: [{ required: true, message: this.$t('pleaseInput') }, { validator: checkIsRangeInteger(1, 2147483647) }],
        fileReprogramType: [{ required: true, message: this.$t('pleaseSelect') }],
        primitiveVersion: [{ required: true, validator: validatePrimitive,}],
      },
      isManualEntry: false,
      dllNameDictCode: [],
      disableOriginVersion: true,
      verisonList: []
    }
  },
  watch: {
    'formUploadFile.hashAlgorithm': {
      handler () {
        // 切换算法后 重新上传文件
        this.fileInfor = { fileObject: {} }
        this.$refs.uploadPlug.resetUpload()
      }
    },
    'fileInfor.fileObject.fileId': {
      handler (val) {
        this.$refs.createModal.clearValidate('fileName')
      }
    }
  },
  methods: {
    handleChange(val){
      if(val.length>1){
        this.$message.warning('原始版本只能有一个')
        val.pop()
        return
      }
    },
    addFiles () {
      if (this.upgradePackType === 1) {
        this.disableOriginVersion = true
        if (this.uploadRules.primitiveVersion) {
          delete this.uploadRules.primitiveVersion
        }
      } else if (this.upgradePackType === 2) {
        this.disableOriginVersion = false
        this.uploadRules.primitiveVersion = [{ required: true, message: this.$t('pleaseInput') },{ validator: checkVersionNameWithOutV(), trigger: 'change', required: true },
        { validator: checkVersionNameWithOutV(), trigger: 'blur', required: true }]
        this.verisonList = []
        this.$api.getMcVersionList({
          ecuId: this.ecuId,
          modelCode: this.modelCode,
          softwareCode: this.softwareCode,
          isConfigFile: this.isConfigFile,
          versionNumber:this.versionNumber

        }).then((res) => {
          this.verisonList = res.data.filter((item) => {
            let hasChosen = false
            this.uploadFile.forEach(item2 => {
              if (item2.primitiveVersion === item) {
                hasChosen = true
              }
            })
            if (hasChosen) {
              return false
            }
            return true
          })
        })
      }
      this.$api.searchFlushType().then(res => {
        this.dllNameDictCode = res.data
      })
      this.fileInfor = { fileObject: {} }
      this.formUploadFile = { ...initForm }
      this.visible = true
    },
    upload () {
      this.$refs.uploadPlug.upload()
    },
    handCancel() {
      this.$refs.createModal.resetFields()
    },
    uploadOk () {
      this.$refs.createModal.validate(valid => {
        if (valid) {
          const vm = this
          const values = { ...vm.formUploadFile }
          if (vm.fileInfor.fileObject.fileId) {
            values.fileId = vm.fileInfor.fileObject.fileId
            values.fileName = vm.fileInfor.fileObject.fileName // 文件名
            if (vm.fileInfor.fileObject.size < 1024 * 1024) {
              values.fileSize = Math.round((vm.fileInfor.fileObject.size / 1024)) + 'KB'
            } else if (vm.fileInfor.fileObject.size >= 1024 * 1024 && vm.fileInfor.fileObject.size < 1024 * 1024 * 1024) {
              values.fileSize = (Math.round((vm.fileInfor.fileObject.size / 1024 / 1024) * 100) / 100) + 'MB'
            } else {
              values.fileSize = (Math.round((vm.fileInfor.fileObject.size / 1024 / 1024 / 1024) * 100) / 100) + 'GB'
            }

            values.versionType = 2 // 配置文件2 零件版本的升级包1
            values.resourceType = 10
            // 如果是自动填充需要用生成的摘要值
            if (!vm.isManualEntry) {
              values.checksum = vm.fileInfor.fileObject[vm.digestAlgorithm[vm.formUploadFile.hashAlgorithm]]
            }
            // 手动输入时需要校验
            if (values.checksum !== vm.fileInfor.fileObject[vm.digestAlgorithm[vm.formUploadFile.hashAlgorithm]]) {
              vm.$message.warning(vm.$t('summaryIn'))
              return
            }
            vm.confirmLoading = true
            vm.$emit('saveFile', values)
            vm.visible = false
            vm.fileInfor = { fileObject: { uploadLoadding: false } }
            vm.$refs.uploadPlug.resetUpload()
            vm.confirmLoading = false
          } else {
            vm.$message.warning(vm.$t('pleaseUpload') + vm.$t('file'))
          }
        } else {
          return false;
        }
      })

    },
  },
}
</script>
<style lang="less">
.model-content{
  .ant-form-item{
    margin-bottom: 0;
  }
  .ant-form-item-required::before {
    font-weight: normal;
  }
  .hideprim {
    .ant-form-item-required::before {
      display: none;
    }
  }
} 
</style>
